package cn.water.rocketmq.common;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

/**
 * 生产者  发消息
 */
public class MyProducer {
    @Test
    public void sendMessage() throws Exception{
        DefaultMQProducer producer = new DefaultMQProducer();
        producer.setNamesrvAddr("localhost:9876");
        producer.setProducerGroup("test-group-1");
        producer.start();
        //创建消息
        Message message = new Message();
        //消息内容
        String content = "这是我的一个消息";
        //转为二进制
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        message.setBody(bytes);
        message.setTopic("test-topic-1");
        message.setKeys("orderSn:2024/7/29");
        //发送端开始发送消息
        SendResult send = producer.send(message,20000);
        //发送后获取到 发到了哪里
        MessageQueue messageQueue = send.getMessageQueue();
        System.out.println("messageQueue:"+messageQueue);
        //消息发送的状态
        SendStatus sendStatus = send.getSendStatus();
        System.out.println("sendStatus:"+sendStatus);
        //消息自动生成的id
        String msgId = send.getMsgId();
        System.out.println("msgId:"+msgId);
        //关闭连接
        producer.shutdown();
    }
}
